package com.example.movie_shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movie_shop.entry.Cart;
import com.example.movie_shop.entry.Movie;
import com.example.movie_shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/carts")
public class CartController {

    @Autowired
    public CartService cartService;

    @RequestMapping("/add_cart")
    public boolean addCart(Cart cart){
        if(!isAdded(cart)){
            //1.如果没有添加，执行添加
            return cartService.save(cart);
        }else {
            //2.如果已经添加执行更新操作
            //查询条件
            QueryWrapper<Cart> wrapper = new QueryWrapper<>();
            wrapper.eq("uid",cart.getUid());
            wrapper.eq("movie_id",cart.getMovieId());
            //更新信息
            Cart cart1 = cartService.getOne(wrapper);
            int num;
            if(cart.getNum()>1)
                num = cart1.getNum()+cart.getNum();
            else
                num = cart1.getNum()+1;
            cart1.setNum(num);
            cart1.setSubPrice(cart1.getPrice()*num);
            //执行更新
            return cartService.update(cart1,wrapper);
        }
    }

    public boolean isAdded(Cart cart){
        return cartService.isAdd(cart);
    }

//    @RequestMapping("/get_user_cart_tatal")
//    public long gerUserCartTotal(){
//        return cartService.getTotal(uid);
//    }

    @RequestMapping("/show_carts")
    public List<Cart> showCarts(Integer uid){
        Page page = new Page(1,4);
        QueryWrapper<Cart> q = new QueryWrapper<Cart>();
        q.eq("uid",uid);
        Page cart_page = cartService.page(page,q);
        List<Cart> carts = cart_page.getRecords();
        return carts;
    }

}
